package com.winway.sixbook.ui;

import com.winway.sixbook.HomeActivity;
import com.winway.sixbook.R;
import com.winway.sixbook.custom.CloseActivityClass;
import com.winway.sixbook.service.CounterDataManager;
import android.app.DatePickerDialog;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Dialog;
import java.util.Calendar;
import android.widget.DatePicker;

public class EditCounterActivity extends Activity {
	
	private static final String TAG = "CounterActivity";

	private int old=0;
	private String id;
	private TextView t;
	private EditText countername;
	private EditText counternum;
	private Button editbutton = null;
	private Button delbutton = null;
	private CounterDataManager counterDataManager;
	private EditText beginDate=null;
	private ImageButton top_tbn_fanhui;
	private Button top_tbn_xinzeng;
	private TextView title;
	AlertDialog builder = null;
	private boolean flagnew = false;
	private Calendar c = null;
	private EditText endDate = null;
	private EditText targetnum = null;
	 
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.editcounteractivity);
		CloseActivityClass.activityList.add(this);
		
		Intent intent1 = getIntent();
		
		id=intent1.getStringExtra("id");
		countername=(EditText) findViewById(R.id.countername);
		counternum=(EditText) findViewById(R.id.counternum);
		top_tbn_fanhui = (ImageButton)findViewById(R.id.nagivate_btn_left);
        top_tbn_xinzeng = (Button)findViewById(R.id.navigate_btn_right);
        beginDate =(EditText)findViewById(R.id.beginDate);
        title = (TextView)findViewById(R.id.title);
        endDate =(EditText)findViewById(R.id.endDate);
        targetnum =(EditText)findViewById(R.id.targetnum);
		
		if(counterDataManager==null){
			counterDataManager= new CounterDataManager(this);
			counterDataManager.openDataBase();
		}
		if(id!=null){
			Cursor cursor =counterDataManager.fetchCounterData(Integer.valueOf(id));
			if(cursor.getColumnCount()>0){
				cursor.moveToFirst(); 
				old=cursor.getInt(cursor.getColumnIndex("countnum"));
				
				countername.setText(cursor.getString(cursor.getColumnIndex("countname")));
				counternum.setText(cursor.getString(cursor.getColumnIndex("countnum")));
				beginDate.setText(cursor.getString(cursor.getColumnIndex("begindate")));
				endDate.setText(cursor.getString(cursor.getColumnIndex("enddate")));
				targetnum.setText(cursor.getString(cursor.getColumnIndex("targetnum")));

				delbutton = (Button)findViewById(R.id.delcounterbutton);  
				delbutton.setVisibility(View.VISIBLE);
				delbutton.setOnClickListener(delListener); 
			}
		}
		editbutton = (Button)findViewById(R.id.savecounterbutton);  
		editbutton.setOnClickListener(mListener); 
		
		top_tbn_fanhui.setOnClickListener(mListener);
        title.setText("计数器类型设置");
        top_tbn_xinzeng.setOnClickListener(mListener); 
        beginDate.setOnClickListener(mListener);
        endDate.setOnClickListener(mListener);
	}
	
	/**
     * 创建日期及时间选择对话框
     */
    @Override
    protected Dialog onCreateDialog(int id) {
        Dialog dialog = null;
        switch (id) {
        	case 0:
            c = Calendar.getInstance();
            dialog = new DatePickerDialog(
                this,
                new DatePickerDialog.OnDateSetListener() {
                    public void onDateSet(DatePicker dp, int year,int month, int dayOfMonth) {
                    	beginDate.setText(year + "-" + (month+1) + "-" + dayOfMonth );
                    }
                }, 
                c.get(Calendar.YEAR), // 传入年份
                c.get(Calendar.MONTH), // 传入月份
                c.get(Calendar.DAY_OF_MONTH) // 传入天数
            );
            break;
            
        	case 1:
                c = Calendar.getInstance();
                dialog = new DatePickerDialog(
                    this,
                    new DatePickerDialog.OnDateSetListener() {
                        public void onDateSet(DatePicker dp, int year,int month, int dayOfMonth) {
                        	endDate.setText(year + "-" + (month+1) + "-" + dayOfMonth );
                        }
                    }, 
                    c.get(Calendar.YEAR), // 传入年份
                    c.get(Calendar.MONTH), // 传入月份
                    c.get(Calendar.DAY_OF_MONTH) // 传入天数
                );
                break;
        
        }
        return dialog;
    }

	
	
	OnClickListener mListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
				case R.id.savecounterbutton:
					if(dataValid()){
						if(id==null||id.equals("")){
							counterSave();
						}else{
							update(Integer.valueOf(id));
						}
					}
				break;
				case R.id.navigate_btn_right:
					Intent intent = new Intent(EditCounterActivity.this, SetCounterListActivity.class);
					startActivity(intent);
					finish();
				break; 
				case R.id.nagivate_btn_left:
					Intent intent1 = new Intent(EditCounterActivity.this, SetCounterListActivity.class);
					startActivity(intent1);
					finish();
				break;
				
				case R.id.beginDate:
					Log.v(TAG, "onfocus");
					showDialog(0);
				break;
				case R.id.endDate:
					Log.v(TAG, "onfocus");
					showDialog(1);
				break;
			}
		}
	};
	 
	OnClickListener delListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
				case R.id.delcounterbutton:
					del(Integer.valueOf(id));
					break; 
				 
			}
		}
	};
	 
	public boolean dataValid() {
		String name = countername.getText().toString().trim();
		String num = counternum.getText().toString().trim();
		String num1 = targetnum.getText().toString().trim();
		String date1 = beginDate.getText().toString().trim();
		String date2 = endDate.getText().toString().trim();
		
		if (null== name || "".equals(name)) {
			Toast.makeText(this, getString(R.string.jsqtype_empty), Toast.LENGTH_SHORT).show();
			return false;
		}else if (null== num || "".equals(num)) {
			Toast.makeText(this, getString(R.string.jsqvalue_empty), Toast.LENGTH_SHORT).show();
			return false;
		}else if (null== num1 || "".equals(num1)) {
			Toast.makeText(this, getString(R.string.targetnum_empty), Toast.LENGTH_SHORT).show();
			return false;
		}else if (null== date1 || "".equals(date1)) {
			Toast.makeText(this, getString(R.string.date1_empty), Toast.LENGTH_SHORT).show();
			return false;
		}else if (null== date2 || "".equals(date2)) {
			Toast.makeText(this, getString(R.string.date2_empty), Toast.LENGTH_SHORT).show();
			return false;
		}
		return true;
	}
	
	private void counterSave()
	{
		String name = countername.getText().toString().trim();
		String num = counternum.getText().toString().trim();
		String num1 = targetnum.getText().toString().trim();
		String date1 = beginDate.getText().toString().trim();
		String date2 = endDate.getText().toString().trim();
	
		if(num==null)num="0";
		if(num1==null)num1="0";
		
		counterDataManager.openDataBase();
		long flag = counterDataManager.insertCounterData(Integer.valueOf(num), name,Integer.valueOf(num1),date1,date2);
		if (flag == -1) {
			Toast.makeText(this, getString(R.string.save_fail),Toast.LENGTH_SHORT).show();
		}else{
			Toast.makeText(this, getString(R.string.save_sucess),Toast.LENGTH_SHORT).show();
		}
		
		Intent counterset = new Intent(EditCounterActivity.this,SetCounterListActivity.class);
		startActivity(counterset);
	}
	  
	private void update(int id)
	{
		String name = countername.getText().toString().trim();
		String num = counternum.getText().toString().trim();
		String num1 = targetnum.getText().toString().trim();
		String date1 = beginDate.getText().toString().trim();
		String date2 = endDate.getText().toString().trim();
		if(num==null)num="0";
		if(num1==null)num1="0";
		
		counterDataManager.openDataBase();
		boolean  flag=counterDataManager.updateCounterData2(id,Integer.valueOf(num),name,Integer.valueOf(num1),date1,date2);
		
		if (!flag) {
			Toast.makeText(this, getString(R.string.save_fail),Toast.LENGTH_SHORT).show();
		}else{
			Toast.makeText(this, getString(R.string.save_sucess),Toast.LENGTH_SHORT).show();
		}
		Intent counterset = new Intent(EditCounterActivity.this,SetCounterListActivity.class);
		startActivity(counterset);
	}
	
	private void del(final int id)
	{
		builder = new AlertDialog.Builder(EditCounterActivity.this)
		.setIcon(R.drawable.ic_launcher)
		.setTitle("温馨提示：")
		.setMessage("您是否要删除该数据吗")
		.setPositiveButton("确定",new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int whichButton) {
				counterDataManager.openDataBase();
				flagnew = counterDataManager.deleteData(id);
				if (!flagnew) {
					Toast.makeText(EditCounterActivity.this, getString(R.string.del_fail),Toast.LENGTH_SHORT).show();
				}else{
					Toast.makeText(EditCounterActivity.this, getString(R.string.del_sucess),Toast.LENGTH_SHORT).show();
				}
				
				Intent counterset = new Intent(EditCounterActivity.this,SetCounterListActivity.class);
				startActivity(counterset);
			}
		}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog,
					int whichButton) {
				builder.dismiss();
			}
		}).show();
		
	}
	/**
	 * 捕捉back
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			Intent counter1 = new Intent(EditCounterActivity.this, SetCounterListActivity.class);
			startActivity(counter1);
			finish();
			return true;
		}
		
		return super.onKeyDown(keyCode, event);
	}


	
}
